import { forIn } from 'lodash-es'
import * as spritejs from 'spritejs'
import { updateEnterScreen, updateLeaveScreen } from '../screens'
import { cars } from './Car'
import { parkSpacesList } from './ParkSpace'
import {
    drawEnterAndLeave,
    enterDoor,
    enterPolyline,
    leaveDoor,
    leavePolyline,
} from './doors'
import { drawPark } from './drawPark'
import { selectedCar } from './selectedCar'
const { Scene, Sprite, Polyline, Rect, Label } = spritejs

export const keyDowned = {
    ArrowUp: false,
    ArrowDown: false,
    ArrowLeft: false,
    ArrowRight: false,
}

// 全局变量
export let layer = null

// 注册事件
const registerEvent = function () {
    document.addEventListener('keydown', (e) => {
        if (keyDowned[e.key]) return
        if (keyDowned.hasOwnProperty(e.key)) {
            keyDowned[e.key] = true
            e.preventDefault()
        }
    })
    document.addEventListener('keyup', (e) => {
        if (!keyDowned[e.key]) return
        if (keyDowned.hasOwnProperty(e.key)) {
            keyDowned[e.key] = false
            e.preventDefault()
        }
    })
}

// 渲染
const render = () => {
    // 执行车辆的移动
    forIn(keyDowned, (v, k) => {
        if (selectedCar && v && selectedCar[k]) {
            selectedCar[k]()
            // 判断是否要进入停车场
            if (!enterDoor.opened) {
                const res = selectedCar.isIn(enterPolyline)
                if (res && enterDoor && !enterDoor.opened) {
                    // 开门并且5秒后关门
                    enterDoor.open()
                    updateEnterScreen(selectedCar.id)
                    setTimeout(() => {
                        enterDoor.close()
                    }, 5000)
                }
            }
            // 判断是否要离开停车场
            if (!leaveDoor.opened) {
                const res = selectedCar.isIn(leavePolyline)
                if (res && leaveDoor && !leaveDoor.opened) {
                    updateLeaveScreen(selectedCar.id)
                    // 开门并且5秒后关门
                    // leaveDoor.open()
                    // setTimeout(() => {
                    //     leaveDoor.close()
                    // }, 5000)
                }
            }

            // 判断是否停在了车位上或者离开了车位
            if (!selectedCar.parkSpaceId) {
                for (let i = 0; i < parkSpacesList.length; i++) {
                    const parkSpace = parkSpacesList[i]
                    const res = selectedCar.isIn(parkSpace.rect)
                    if (res) {
                        // 更改该车位的边框颜色
                        parkSpace.rect.attr('strokeColor', '#409eff')
                        // 过了0.3秒还在车位上，就认为是停好了
                        setTimeout(() => {
                            if (
                                !selectedCar.parkSpaceId &&
                                selectedCar.isIn(parkSpace.rect)
                            ) {
                                selectedCar.setParkSpaceId(
                                    parkSpace.id,
                                    parkSpace.options.parkSpaceInfo
                                )
                            }
                        }, 300)
                        break
                    } else {
                        // 如果没有车停在这里
                        const parkSpaceId = parkSpace.id
                        const index = cars.findIndex(
                            (item) => item.parkSpaceId === parkSpaceId
                        )
                        if (index === -1) {
                            parkSpace.rect.attr('strokeColor', '#eee')
                        }
                    }
                }
            } else {
                // 判断是否离开了车位
                const parkSpace = parkSpacesList.find(
                    (item) => item.id === selectedCar.parkSpaceId
                )
                if (parkSpace && !selectedCar.isIn(parkSpace.rect)) {
                    // 离开了0.3秒后，就认为是离开了车位
                    setTimeout(() => {
                        if (
                            selectedCar.parkSpaceId &&
                            !selectedCar.isIn(parkSpace.rect)
                        ) {
                            selectedCar.setParkSpaceId(
                                undefined,
                                parkSpace.options.parkSpaceInfo
                            )
                        }
                    }, 300)
                }
            }
        }
    })
    // 渲染
    layer.render()
    // 下一帧
    requestAnimationFrame(render)
}

// 主函数
export const main = async function (containerDom) {
    if (!containerDom) return

    const container = containerDom
    const scene = new Scene({
        container,
        width: 1200,
        height: 1000,
        mode: 'stickyTop',
        autoRender: false,
    })

    layer = scene.layer()
    layer.attr({
        bgcolor: '#999',
    })
    drawPark(layer)
    drawEnterAndLeave(layer)

    // drawParkSpaces(layer)
    // setSelectedCar(new Car(layer, 'car1'))
    // new Car(layer, 'car2')

    render()

    registerEvent()
}
